package com.lujieni.threadpool.config;

import com.alibaba.fastjson.JSON;
import com.lujieni.threadpool.dao.ThreadPoolTaskDao;
import com.lujieni.threadpool.po.ThreadPoolTaskPO;
import com.lujieni.threadpool.service.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author：小鹿爱吃鱼
 * @Date: 2025/2/23 17:40
 * @Description:
 */
@Component
@Slf4j
public class DatabaseRejectedExecutionHandler implements RejectedExecutionHandler {
    private static final Logger logger = LoggerFactory.getLogger(DatabaseRejectedExecutionHandler.class);

    @Autowired
    private ThreadPoolTaskDao threadPoolTaskDao;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        // 获取任务信息（如果 Runnable 实现了 toString() 方法，可以获取有用的信息）
        String taskInfo = r.toString();
        ThreadPoolTaskPO taskPO = JSON.parseObject(taskInfo, ThreadPoolTaskPO.class);
        logger.info(taskPO.toString());
        if(taskPO.getId() == null){
            taskPO.setId(snowflakeIdWorker.nextId());
            taskPO.setActive(1);
            taskPO.setCreateTime(new Date());
            taskPO.setModifyTime(new Date());
            taskPO.setCreateUserCode("181268");
            taskPO.setModifyUserCode("181268");
            threadPoolTaskDao.insert(taskPO);
        }
    }
}
